package com.yantong.controller.finance;

import com.alibaba.fastjson.JSONObject;
import com.yantong.annotation.Log;
import com.yantong.constant.CashStatus;
import com.yantong.constant.ConfigKey;
import com.yantong.controller.BaseController;
import com.yantong.result.ResultVo;
import com.yantong.utils.DateUtils;
import com.yantong.utils.PageUtils;
import com.yantong.utils.excel.ExcelHelper;
import com.yantong.pojo.WdListParams;
import com.yantong.pojo.Withdrawals;
import com.yantong.service.WithdrawalsService;
import com.yantong.pojo.OrderWithdrawals;
import com.yantong.pojo.PlatformConfig;
import com.yantong.service.ConfigService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 提现控制类
 * @author kanghaixin
 * @date 2018/9/16.20:08
 */
@Controller
@RequestMapping("/finance/withdrawals")
public class WithdrawalsController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(WithdrawalsController.class);
    private static final String prefix = "finance/withdrawals";
    @Autowired
    private WithdrawalsService withdrawalsService;
    @Autowired
    private ConfigService configService;
    /**
     * 提现记录页面
     * @param model
     * @return
     */
    @RequiresPermissions("finance:withdrawals:withdrawals")
    @GetMapping()
    public String withdrawals(Model model) {
        model.addAllAttributes(getCentreIdModelInfo());
        return prefix +"/withdrawals";
    }


    /**
     * 获取未审核提现记录
     * @param params
     * @param offset
     * @param limit
     * @return
     */
    @RequiresPermissions("finance:withdrawals:withdrawals")
    @GetMapping("/list")
    @ResponseBody
    public PageUtils<Withdrawals> listUncheckedWithdrawals(WdListParams params, int offset, int limit) {
        if (params.getStart() != null) {
            params.setStart(DateUtils.getDateStartTime(params.getStart()));
        }
        if (params.getEnd() != null) {
            params.setEnd(DateUtils.getDateEndTime(params.getEnd()));
        }
       /* //如果角色为供应商并且centreid不为空 则查询 站点供应商数据
        if(getUserCentreId()!=null && null != params && "1".equals(params.getRole())){
        	params.setSuppliertype("1");//站点供应商
        }else if(getUserCentreId()==null && null != params && "1".equals(params.getRole())){
        	params.setSuppliertype("0");//平台供应商
        }*/
        if(getUserCentreId()!=null && null != params && "1".equals(params.getRole())){
        	params.setSuppliertype("1");//站点供应商
        }
        Long teamId = getUserTeamId();
//        if(null != teamId){
//            params.setTeamId(teamId);
//        }
        params.setRole("");
        PlatformConfig config = configService.getConfigByKey(ConfigKey.TRADE_CONFIG.name(), getUserCentreId());
        JSONObject configValue = JSONObject.parseObject(config.getConfigValue());
        params.setCashdays(configValue.get("cashdays").equals("")?0:Integer.parseInt(configValue.get("cashdays")+""));
        return withdrawalsService.listWithdrawals(params, offset,limit);
    }
    
    /**
     * 根据状态查找第三方代付记录表
     * @param transts
     * @param rowBounds
     * @return
     */
    @RequiresPermissions("finance:withdrawals:withdrawals")
    @GetMapping("/getOrderWithdrawalsByTransts")
    @ResponseBody
    public PageUtils<OrderWithdrawals> getOrderWithdrawalsByTransts(WdListParams params, int offset, int limit) {
    	 if (params.getStart() != null) {
             params.setStart(DateUtils.getDateStartTime(params.getStart()));
         }
         if (params.getEnd() != null) {
             params.setEnd(DateUtils.getDateEndTime(params.getEnd()));
         }
         PlatformConfig config = configService.getConfigByKey(ConfigKey.TRADE_CONFIG.name(), getUserCentreId());
         JSONObject configValue = JSONObject.parseObject(config.getConfigValue());
         params.setCashdays(configValue.get("cashdays").equals("")?0:Integer.parseInt(configValue.get("cashdays")+""));
    	return withdrawalsService.getOrderWithdrawalsByTransts(params, offset, limit);
    }

    /**
     * 提现记录导出
     * @param params
     * @param response
     */
    @RequiresPermissions("finance:withdrawals:export")
    @GetMapping("/export")
    public void exportWithdrawals(WdListParams params, HttpServletResponse response){
        if (params.getStart() != null) {
            params.setStart(DateUtils.getDateStartTime(params.getStart()));
        }
        if (params.getEnd() != null) {
            params.setEnd(DateUtils.getDateEndTime(params.getEnd()));
        }
        List<List<Object>> resultData = new ArrayList<>();
        String[] head = {"提现ID", "提现单号", "姓名", "会员ID","供应商名称", "手机号码","提现方式","提现状态", "提现金额","手续费", "申请时间","审核时间","审核人","打款时间","打款人"};
        resultData.add(0, Arrays.asList(head));
       /* //如果角色为供应商并且centreid不为空 则查询 站点供应商数据
        if(getUserCentreId()!=null && null != params && "1".equals(params.getRole())){
        	params.setSuppliertype("1");//站点供应商
        }else if(getUserCentreId()==null && null != params && "1".equals(params.getRole())){
        	params.setSuppliertype("0");//平台供应商
        }*/
        if(getUserCentreId()!=null && null != params && "1".equals(params.getRole())){
        	params.setSuppliertype("1");//站点供应商
        }
        List<Withdrawals> list = withdrawalsService.listWithdrawals(params);
        if (CollectionUtils.isNotEmpty(list)) {
            for (Withdrawals wds: list) {
                if (wds == null) {
                    continue;
                }
                List<Object> row = new ArrayList<>();
                row.add(wds.getId());
                row.add(wds.getApplyno());
                row.add(wds.getRealname());
                row.add(wds.getMid());
                if(wds.getRole()==1) {
                	 row.add(wds.getName().equals("")?"": wds.getName());
                }else {
                	row.add("");
                }
                row.add(wds.getMobile());
                row.add("微信钱包");
                row.add(CashStatus.get(wds.getStatus()));
                row.add(wds.getMoney());
                row.add(wds.getCommissionMoney());
                row.add(wds.getCreateTime());
                row.add(wds.getCheckTime());
                row.add(wds.getCheckName());
                row.add(wds.getPayTime());
                row.add(wds.getPayName());
                resultData.add(row);
            }
        }
        String fileName = "提现申请记录_" + DateUtils.format(new Date(), "yyyyMMddHHmmss");
        try {
            ExcelHelper.exportExcel(response, fileName, "提现申请记录", resultData);
        } catch (IOException e) {
            logger.info("export withdrawals log error:{}", e.getMessage());
        }
    }
    
    /**
     * 打款中导出
     * @param params
     * @param response
     */
    @RequiresPermissions("finance:withdrawals:export")
    @GetMapping("/exportbankProcess")
    public void exportbankProcess(WdListParams params, HttpServletResponse response){
        if (params.getStart() != null) {
            params.setStart(DateUtils.getDateStartTime(params.getStart()));
        }
        if (params.getEnd() != null) {
            params.setEnd(DateUtils.getDateEndTime(params.getEnd()));
        }
        List<List<Object>> resultData = new ArrayList<>();
        String[] head = {"ID", "卡号", "姓名", "提现金额","手续费","打款金额","时间","状态"};
        resultData.add(0, Arrays.asList(head));
        
        List<OrderWithdrawals> list = withdrawalsService.getOrderWithdrawalsByTranstsList(params);
        if (CollectionUtils.isNotEmpty(list)) {
            for (OrderWithdrawals obj: list) {
                if (obj == null) {
                    continue;
                }
                List<Object> row = new ArrayList<>();
                row.add(obj.getId());
                row.add(obj.getBankcard());
                row.add(obj.getMemrealnm());
                row.add(obj.getCashamt());
                row.add(obj.getServcarge());
                row.add(obj.getTranceamt());
                row.add(obj.getCredt());
                row.add("打款中");
                resultData.add(row);
            }
        }
        String fileName = "打款中_" + DateUtils.format(new Date(), "yyyyMMddHHmmss");
        try {
            ExcelHelper.exportExcel(response, fileName, "打款中", resultData);
        } catch (IOException e) {
            logger.info("export withdrawals log error:{}", e.getMessage());
        }
    }
    
    /**
     * 获取某会员对应的提现申请记录 
     * @author xiangyi
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("finance:withdrawals:withdrawals")
    @GetMapping("/withdrawalsToMid/{id}")
    public String withdrawalsToMid(@PathVariable String id, Model model) {
        model.addAttribute("mid", id);
        return prefix + "/withdrawalsToMid";
    }

    /**
     * 审核通过
     * @param bwId
     * @return
     */
    @Log(module = "提现管理", operation = "审核通过")
    @ResponseBody
    @PostMapping("/checkPass")
    @RequiresPermissions("finance:withdrawals:pass")
    public ResultVo checkPass(Long bwId) {
        if (bwId == null) {
            return ResultVo.error();
        }
        Withdrawals wd = new Withdrawals();
        wd.setId(bwId);
        wd.setCheckTime(new Date());
        wd.setCheckId(getUserId());
        wd.setCheckName(getNikeName());
        wd.setStatus(CashStatus.CHECKED.getCode());
        if (withdrawalsService.updateWithdrawals(wd)< 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }

    /**
     * 审核拒绝
     * @param bwId
     * @return
     */
    @Log(module = "提现管理", operation = "审核拒绝")
    @ResponseBody
    @PostMapping("/refuse")
    @RequiresPermissions("finance:withdrawals:refuse")
    public ResultVo refuse(Long bwId) {
        if (bwId == null) {
            return ResultVo.error();
        }
        if (withdrawalsService.cashRefuse(bwId, getUserId(), getNikeName())< 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }


    /**
     * 批量审核通过
     * @param ids
     * @return
     */
    @Log(module = "提现管理", operation = "批量审核通过")
    @ResponseBody
    @PostMapping("/batchCheck")
    @RequiresPermissions("finance:withdrawals:batchPass")
    public ResultVo batchCheck(@RequestParam("ids[]") Long[] ids) {
        if (ids == null || ids.length <1) {
            return ResultVo.error();
        }
        Date checkTime = new Date();
        for (Long id: ids) {
            Withdrawals wd = new Withdrawals();
            wd.setId(id);
            wd.setCheckTime(checkTime);
            wd.setCheckId(getUserId());
            wd.setCheckName(getNikeName());
            wd.setStatus(CashStatus.CHECKED.getCode());
            withdrawalsService.updateWithdrawals(wd);
        }
        return ResultVo.ok();
    }

    /**
     * 微信打款
     * @param bwId
     * @return
     */
    @Log(module = "提现管理", operation = "微信打款")
    @ResponseBody
    @PostMapping("/wxPay")
    @RequiresPermissions("finance:withdrawals:wxPay")
    public ResultVo wxPay(Long bwId) {
        if (bwId == null) {
            return ResultVo.error();
        }
        if (withdrawalsService.wxPay(bwId,getUserId(), getNikeName())< 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }

    /**
     * 线下打款
     * @param bwId
     * @return
     */
    @Log(module = "提现管理", operation = "线下打款")
    @ResponseBody
    @PostMapping("/offlinePay")
    @RequiresPermissions("finance:withdrawals:offlinePay")
    public ResultVo offlinePay(Long bwId) {
        if (bwId == null) {
            return ResultVo.error();
        }
        if (withdrawalsService.offlinePay(bwId, getUserId(),getNikeName())< 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }

    /**
     * 微信批量打款
     * @param ids
     * @return
     */
    @Log(module = "提现管理", operation = "微信批量打款")
    @PostMapping("/batchWxPay")
    @ResponseBody
    @RequiresPermissions("finance:withdrawals:batchWxPay")
    public ResultVo batchWxPay(@RequestParam("ids[]") Long[] ids) {
        if (ids == null || ids.length <1) {
            return ResultVo.error();
        }
        for (Long id: ids) {
            withdrawalsService.wxPay(id, getUserId(), getNikeName());
        }
        return ResultVo.ok();
    }

    /**
     * 线下批量打款
     * @param ids
     * @return
     */
    @Log(module = "提现管理", operation = "线下批量打款")
    @PostMapping("/batchOfflinePay")
    @ResponseBody
    @RequiresPermissions("finance:withdrawals:batchOfflinePay")
    public ResultVo batchOfflinePay(@RequestParam("ids[]") Long[] ids) {
        if (ids == null || ids.length <1) {
            return ResultVo.error();
        }
        for (Long id: ids) {
            withdrawalsService.offlinePay(id, getUserId(), getNikeName());
        }
        return ResultVo.ok();
    }

    
    /**
     * 批量、单个银行卡打款
     * @param ids
     * @return
     */
    @Log(module = "提现管理", operation = "批量、单个银行卡打款")
    @PostMapping("/batchBankPay")
    @ResponseBody
    @RequiresPermissions("finance:withdrawals:batchBankPay")
    public ResultVo batchBankPay(@RequestParam("ids[]") Long[] ids) {
        if (ids == null || ids.length <1) {
            return ResultVo.error();
        }
        for (Long id: ids) {
            // withdrawalsService.bankPay(id, getUserId(), getNikeName());
        	//withdrawalsService.hjBankPay(id, getUserId(), getNikeName());
            withdrawalsService.yfzBankPay(id, getUserId(), getNikeName());
        }
        return ResultVo.ok();
    }
    
    /**
     * 供应商/会员提现  批量更新
     * @param ids
     * @return
     */
    @Log(module = "提现管理", operation = "供应商/会员提现")
    @PostMapping("/batchUpdateBankPay")
    @ResponseBody
    @RequiresPermissions("finance:withdrawals:callback")
    public ResultVo batchUpdateBankPay(@RequestParam("ids[]") Long[] ids) {
        if (ids == null || ids.length <1) {
            return ResultVo.error();
        }
        for (Long id: ids) {
            withdrawalsService.batchUpdateBankPay(id, getUserId(), getNikeName());
        }
        return ResultVo.ok();
    }
    
    
//    /**
//     * 站点提现 批量更新
//     * @param ids
//     * @return
//     */
//    @Log(module = "提现管理", operation = "站点提现")
//    @PostMapping("/batchCentrUpdateBankPay")
//    @ResponseBody
//    @RequiresPermissions("centre:cashLog:callback")
//    public ResultVo batchCentrUpdateBankPay(@RequestParam("ids[]") Long[] ids) {
//        if (ids == null || ids.length <1) {
//            return ResultVo.error();
//        }
//        for (Long id: ids) {
//            withdrawalsService.batchCentrUpdateBankPay(id, getUserId(), getNikeName());
//        }
//        return ResultVo.ok();
//    }
    
    
   
}
